/**
 * @author   thienchau
 * @time     5:39:36 PM Jan 30, 2013
 * @filename Ulti.java
 */

package com.cdn.allmobilestore.ulti;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;

import com.cdn.allmobilestore.model.AppInfo;

public class Ulti {

	public static boolean isNetworkAvailable(Context context) {
		return NetworkChangeReceiver.isConnected(true);
		
	}

	public static String getImei(Context context) {
		String identifier = null;
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		if (telephonyManager != null) {
			identifier = telephonyManager.getDeviceId();
		}
		if (TextUtils.isEmpty(identifier)) {
			identifier = Secure.getString(context.getContentResolver(),
					Secure.ANDROID_ID);
		}
		Log.i("phone imei", identifier);

		return identifier;
	}
	
	public static String getUsername(){
	    AccountManager manager = AccountManager.get(GlobalApplication._()); 
	    Account[] accounts = manager.getAccountsByType("com.google"); 
	    List<String> possibleEmails = new LinkedList<String>();

	    for (Account account : accounts) {
	      // TODO: Check possibleEmail against an email regex or treat
	      // account.name as an email address only for certain account.type values.
	      possibleEmails.add(account.name);
	    }

	    if(!possibleEmails.isEmpty() && possibleEmails.get(0) != null){
	        String email = possibleEmails.get(0);
	        Log.i("phone email", email);
	        if(email != null)
	            return email;
	        else
	            return null;
	    }else
	        return null;
	}	
	
	
	// Fast Implementation
	public static String inputStreamToString(InputStream is) {
		  String s = "";
		    String line = "";
		    
		    // Wrap a BufferedReader around the InputStream
		    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		    
		    // Read response until the end
		    try {
				while ((line = rd.readLine()) != null) { s += line; }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		    // Return full string
		    return s;
	}

	
	public static String getDeviceName() {
		String name;
		String manufacturer = Build.MANUFACTURER;
		String model = Build.MODEL;
		if (model.startsWith(manufacturer)) {
			name = capitalize(model);
		} else {
			name = capitalize(manufacturer) + " " + model;
		}
		Log.i("phone name", name);
		return name;
	}

	private static String capitalize(String s) {
		if (s == null || s.length() == 0) {
			return "";
		}
		char first = s.charAt(0);
		if (Character.isUpperCase(first)) {
			return s;
		} else {
			return Character.toUpperCase(first) + s.substring(1);
		}
	}

	public static boolean isOnTop(Activity mActivity) {
		String className = mActivity.getClass().getName();
		ActivityManager am = (ActivityManager) mActivity
				.getSystemService(Activity.ACTIVITY_SERVICE);
		String classNameTop = am.getRunningTasks(1).get(0).topActivity
				.getClassName();
		if (className.equals(classNameTop)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean checkEmail(String inputMail) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+");
		return pattern.matcher(inputMail).matches();
	}

	// dip to px
	public static int convertDensityToPixel(Context context, int dip) {
		return (int) (dip * context.getResources().getDisplayMetrics().density);
	}

	// px to dip
	public static int convertPixelToDensity(Context context, int pixel) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				pixel, context.getResources().getDisplayMetrics());
	}

	public static void CopyStream(InputStream is, OutputStream os)
			throws Exception {
		final int buffer_size = 1024;

		byte[] bytes = new byte[buffer_size];
		for (;;) {
			int count = is.read(bytes, 0, buffer_size);
			if (count == -1)
				break;
			os.write(bytes, 0, count);
		}
	}

	public static void openAnApp(Activity activity, String packageName) {
		Intent LaunchIntent = activity.getPackageManager()
				.getLaunchIntentForPackage(packageName);
		activity.startActivity(LaunchIntent);
	}

	public static ArrayList<AppInfo> getPackages(Activity activity) {
		ArrayList<AppInfo> apps = getInstalledApps(activity, false); /*
																	 * false =
																	 * no system
																	 * packages
																	 */
		final int max = apps.size();
		for (int i = 0; i < max; i++) {
		//	apps.get(i).printMe();
		}
		return apps;
	}

	private static ArrayList<AppInfo> getInstalledApps(Activity activity,
			boolean getSysPackages) {
		ArrayList<AppInfo> res = new ArrayList<AppInfo>();
		List<PackageInfo> packs = activity.getPackageManager()
				.getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue;
			}
			AppInfo newInfo = new AppInfo();
		/*	newInfo.appname = p.applicationInfo.loadLabel(
					activity.getPackageManager()).toString();
			newInfo.pname = p.packageName;
			newInfo.versionName = p.versionName;
			newInfo.versionCode = p.versionCode;
			newInfo.icon = p.applicationInfo.loadIcon(activity
					.getPackageManager());
			res.add(newInfo);
			*/
		}
		return res;
	}
}
